;removeDistortion.pro
;This module physically remaps a FITS image based on the distortion map
;described by the polynomial coefficients determined previously.
;Anton Bondarenko

 FUNCTION RemoveDistortionFun, fileName

    coeff_x = [[-6.894482, 0.016088096, -1.2120916e-005, -9.6082639e-010], $
               [1.0285165, -3.0504694e-005, 2.4924635e-008, 0.0000000000], $
               [-4.3812982e-005, -1.2306293e-009, 0.00000000, 0.00000000], $
               [2.8588192e-008, 0.0000000000, 0.0000000000, 0.0000000000]]

    coeff_y = [[-10.870717, 1.0360583, -4.6905639e-005, 2.4372426e-008], $
               [0.018877309, -2.8669629e-005, 1.4315160e-009, 0.000000], $
               [-1.7221106e-005, 2.6002324e-008, 0.0000000, 0.00000000], $
               [3.5192361e-010, 0.0000000000, 0.0000000000, 0.00000000]]

    ;setting the polynomial coefficients for poly_2d. They are arranged such that
    ;the term in the ith column and jth row represents the coefficient of x^j*y^i.
    ;The functions used by poly_2d take a pixel position (x,y) as input and use
    ;coeff_x and coeff_y to calculate the coordinates  of the
    ;pixel (x',y') whose flux value SHOULD be at position (x,y).

    FITS_array = MRDFITS(fileName, 0, header)   ;read in file
    New_FITS_array = POLY_2D(FITS_array, coeff_x, coeff_y, CUBIC= -0.5) ;adjust fits array for distortion
    outfile = fileName + '~'
    MWRFITS, New_FITS_array, outfile , header, /CREATE  ;write new fits file with adjusted header

    return, 0

 END